package com.wthink.newMain.settings.data.inner.viewmodel

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wthink.hzgj.BusApplication
import com.wthink.hzgj.data.Result
import com.wthink.hzgj.service.DevService
import com.wthink.hzgj.util.toast
import com.wthink.newMain.data.SerialData
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class DataCanViewmodel :ViewModel(){

    val baudRate1 = MutableLiveData<String>()
    val baudRate2 = MutableLiveData<String>()

    val serialList = MutableLiveData(emptyList<SerialData>())
    val baudrateList = MutableLiveData(emptyList<String>())

    fun start(success: (list: List<String>, list1: List<SerialData>) -> Unit) {
        viewModelScope.launch(Dispatchers.IO) {
            val ret = DevService.getCANConfig()
            if (ret is Result.Success) {
                val data = ret.data
                serialList.postValue(data.serialList)
                baudrateList.postValue(data.baudRateList)
                success(data.baudRateList, data.serialList)
            }
        }
    }


    fun start() {
        viewModelScope.launch(Dispatchers.IO) {
            val ret = DevService.getSerialConfig()
            if (ret is Result.Success) {
                val data = ret.data
                serialList.postValue(data.serialList)
                baudrateList.postValue(data.baudRateList)
                callBack.call(data.baudRateList,data.serialList)
            }
        }
    }


    fun config() {
        viewModelScope.launch(Dispatchers.IO) {
            val ret = DevService.setCanConfig(
                baudRate1.value!!, baudRate2.value!!
            )
            if (ret is Result.Success) {
                withContext(Dispatchers.Main) {
                    toast(BusApplication.busContext,"配置成功")
                }
            }
        }
    }

    lateinit var callBack: reqCallBack

    fun setReqCall(reqCallBack: reqCallBack) {
        callBack = reqCallBack
    }

    interface reqCallBack {
        fun call(list: List<String>, list1: List<SerialData>)
    }
}